package cn.geminis.workflow.service.service.engine.interceptor;

import cn.geminis.workflow.service.service.engine.ExtensionElementUtils;
import cn.geminis.workflow.service.service.engine.expression.ExpressionValueContext;
import cn.geminis.workflow.service.service.engine.expression.GeminiExpression;
import cn.geminis.workflow.service.service.engine.expression.GeminiExpressionManager;
import cn.geminis.workflow.service.utils.SpringUtils;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.interceptor.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author puddi
 */
@Service
@RequiredArgsConstructor
public class GeminiStartProcessInstanceInterceptor implements StartProcessInstanceInterceptor {

    private final GeminiExpressionManager expressionManager;

    @Override
    public void beforeStartProcessInstance(StartProcessInstanceBeforeContext processContext) {
        ExtensionElementUtils.get(processContext.getProcess().getExtensionElements(), "instanceName")
                .ifPresentOrElse(nameTemplate -> {
                            var valueContext = SpringUtils.getBean(ExpressionValueContext.class);
                            valueContext.withProcess(processContext);

                            ExtensionElementUtils.get(processContext.getProcess().getExtensionElements(), "dataUrl")
                                    .ifPresent(dataUrl -> {
                                        if (StringUtils.hasText(dataUrl)) {
                                            var dataUrlExpression = ((GeminiExpression) expressionManager.createExpression(dataUrl));
                                            dataUrl = (String) dataUrlExpression.getValue(null);
                                            valueContext.withData(dataUrl);
                                        }
                                    });

                            var expression = ((GeminiExpression) expressionManager.createExpression(nameTemplate));
                            var name = (String) expression.getValue(null);
                            processContext.setProcessInstanceName(name);
                        },
                        () -> {
                            processContext.setProcessInstanceName(processContext.getProcess().getName());
                        });
    }

    @Override
    public void afterStartProcessInstance(StartProcessInstanceAfterContext processContext) {

    }

    @Override
    public void beforeStartSubProcessInstance(StartSubProcessInstanceBeforeContext processContext) {
    }

    @Override
    public void afterStartSubProcessInstance(StartSubProcessInstanceAfterContext processContext) {

    }
}
